package com.ac.service;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ac.exception.RRException;
import com.ac.model.AuthPhone;
import com.ac.util.AuthConf;
import com.ac.util.ConfUtils;
import com.ac.util.StrUtils;
import com.ac.util.ValUtils;
import com.ac.util.sms.TencentSMS;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class AuthPhoneService {

	final MongoTemplate mongo;

	public int getNum(int length) {
		int num = 1;
		for (int i = 1; i < length; i++) {
			num = num * 10;
		}
		return num;
	}

	@Transactional(rollbackFor = Exception.class)
	public int sendCode(AuthPhone authPhone) {
		String phone = authPhone.getPhone();
		long thisTime = System.currentTimeMillis();
		ValUtils.isPhone(phone);
		long preTime = 0;
		AuthPhone phoneInfo = mongo.findOne(new Query(Criteria.where("phone").is(phone)), AuthPhone.class);
		if (phoneInfo != null) {
			preTime = phoneInfo.getPreTime();
		}
		int miao = (int) ((thisTime - preTime) / 1000);
		if (preTime != 0 & miao < AuthConf.phonePreTime)
			throw new RRException(AuthConf.phonePreTime - miao + "秒后再试");
		int num = getNum(AuthConf.codeLength);
		String code = StrUtils.getRandom(num, (10 * num) - 1) + "";
		authPhone.setCode(code);
		authPhone.setPreTime(thisTime);
		
		boolean sendStatus = true;
		if (ConfUtils.pro)
			sendStatus = TencentSMS.sendLogin(phone, code + "");
		else System.out.println(code);
		if (!sendStatus)
			throw new RRException("发送失败，请稍后再试");
		if (phoneInfo == null) {
			authPhone.insert();
			mongo.insert(authPhone);
		} else {
			Update update = new Update();
			update.set("code", code);
			update.set("errNum", 0);
			update.set("preTime", thisTime);
			update.set("updateTime", thisTime);
			mongo.updateFirst(Query.query(Criteria.where("phone").is(phone)), update, AuthPhone.class);
		}
		return AuthConf.phonePreTime;

	}
}
